from sqlalchemy import desc, asc
from sqlalchemy_serializer import SerializerMixin

from app import dBSession
from app.Models.BaseModel import BaseModel
from app.Models.Model import BmFile
from app.Vendor.ApiException import fileSaveErr


class FileForBM(BmFile, BaseModel, SerializerMixin):
    serialize_rules = ('-project_id',)

    def getOne(self, filters, order='id desc', field=()):
        res = dBSession.query(FileForBM).filter(*filters)
        order = order.split(' ')
        if order[1] == 'desc':
            res = res.order_by(desc(order[0])).first()
        else:
            res = res.order_by(asc(order[0])).first()
        if res == None:
            return None
        return res

    """
        添加
        @param obj data 数据
        @return bool
    """

    @staticmethod
    def add(self, data):
        Project = BmFile(**data)
        dBSession.add(Project)
        dBSession.flush()
        return Project.project_id

    @staticmethod
    def update(filters, dataType, data, update_time):
        F = dBSession.query(BmFile).filter_by(project_id=filters).first()
        if (dataType == "data"):
            F.main_file_path = data
        elif (dataType == "label"):
            F.label_file_path = data
        elif (dataType == "coordinate"):
            F.coord_file_path = data
        else:
            raise fileSaveErr()
        F.update_time = update_time
        dBSession.commit()
        return 1
